<?php


namespace PKFrame\DataHandler;
defined('PATH_PK') or die();


class Str
{
    public static function IsExistsInChinese(string $str)
    {
        return preg_match("/[\x7f-\xff]/", $str);
    }

    /**
     * 第一个词首字母小写
     * @param string $str 被处理的字符串
     * @return string
     */
    public static function Lcfirst(string $str = ''): string
    {
        return strtolower(preg_replace("/([^a-z])*(.*)/u", "$1", $str)) . preg_replace("/([^a-z])*([a-z])(.*)/u", "$2$3", $str);
    }

    /**
     * 生成随机字符串
     * @param int $length
     * @param bool $add_length
     * @return string
     */
    public static function Random(int $length = 6, bool $add_length = FALSE): string
    {
        if ($add_length) {
            $string = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ!@#$%^&*-_';
            return Numbers::Random($length, $string);
        } else {
            try {
                return bin2hex(random_bytes($length));
            } catch (\Exception $e) {
                handlerException($e);
            }
            return '';
        }
    }

    /**
     * 隐藏部分字符串
     * @param string $str
     * @param string $replacement
     * @param int $start
     * @param int $length
     * @return string
     */
    public static function SubstrHideReplace(string $str, string $replacement = '*', int $start = 1, int $length = 3): string
    {
        $len = mb_strlen($str, 'utf-8');
        if ($len > intval($start + $length)) {
            $str1 = mb_substr($str, 0, $start, 'utf-8');
            $str2 = mb_substr($str, intval($start + $length), NULL, 'utf-8');
        } else {
            $str1 = mb_substr($str, 0, 1, 'utf-8');
            $str2 = mb_substr($str, $len - 1, 1, 'utf-8');
            $length = $len - 2;
        }
        $new_str = $str1;
        for ($i = 0; $i < $length; $i++) {
            $new_str .= $replacement;
        }
        $new_str .= $str2;
        return $new_str;
    }

    public static function strCutOfTinytext(string $str): string
    {
        return str_cut($str, 250, 255);
    }

    /**
     * 将 URL 传参字符串转换为数据
     * 示例 ： a=1&b=1…
     * @param $arrayString
     * @return array
     */
    public static function ToArray($arrayString): array
    {
        if (empty($arrayString) == false) {
            $result = [];
            $arr = explode('&', $arrayString);
            foreach ($arr as $item) {
                $item_arr = explode('=', $item);
                $result[$item_arr[0]] = $item_arr[1];
            }
            return $result;
        }
        return [];
    }

    public function searchByArray(string $str, array $lists): bool
    {
        //指定的字符串
        preg_match_all('#(' . implode('|', $lists) . ')#', $str, $wordsFound);
//获取匹配到的字符串，array_unique()函数去重。如需获取总共出现次数，则不需要去重
        $wordsFound = array_unique($wordsFound[0]);
        return count($wordsFound) > 0;
    }
}
